<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EdubaseHolidayAdjustmentSchoolApi } from '#/api/edu/base/setting/holidayAdjustmentSchool';

import { ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { CommonStatusEnum } from '@vben/constants';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message, RadioButton, RadioGroup } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteHolidayAdjustmentSchool,
  deleteHolidayAdjustmentSchoolList,
  exportHolidayAdjustmentSchool,
  getHolidayAdjustmentSchoolPage,
  getHolidayAdjustmentSchoolPageDefault,
  updateHolidayAdjustmentSchoolStatus,
} from '#/api/edu/base/setting/holidayAdjustmentSchool';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});
const isDefault = ref(true);
/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建学校假期调休 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑学校假期调休 */
function handleEdit(
  row: EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool,
) {
  formModalApi.setData(row).open();
}

/** 查看学校假期调休 */
function handleDetail(
  row: EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool,
) {
  row.isDefault = isDefault.value;
  detailModalApi.setData(row).open();
}

/** 删除学校假期调休 */
async function handleDelete(
  row: EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool,
) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteHolidayAdjustmentSchool(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除学校假期调休 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteHolidayAdjustmentSchoolList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportHolidayAdjustmentSchool(
    await gridApi.formApi.getValues(),
  );
  downloadFileFromBlobPart({ fileName: '学校补班调休.xls', source: data });
}
/** 切换默认假期和自定义假期 */
function handleChange(e) {
  isDefault.value = e.target.value;
  gridApi.query();
}
/** 切换学校假期状态 */
async function handleStatusChange(
  row: EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool,
) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.updating', [row.infraHolidayId]),
    duration: 0,
  });
  try {
    await updateHolidayAdjustmentSchoolStatus({
      id: row.infraAdjustmentId as number,
      status:
        row.status === CommonStatusEnum.ENABLE
          ? CommonStatusEnum.DISABLE
          : CommonStatusEnum.ENABLE,
    });
    message.success({
      content: $t('ui.actionMessage.updateSuccess', [row.infraHolidayId]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'HolidayAdjustmentSchool-grid',
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return isDefault.value
            ? await getHolidayAdjustmentSchoolPageDefault({
                pageNo: page.currentPage,
                pageSize: page.pageSize,
                ...formValues,
              })
            : await getHolidayAdjustmentSchoolPage({
                pageNo: page.currentPage,
                pageSize: page.pageSize,
                ...formValues,
              });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EdubaseHolidayAdjustmentSchoolApi.HolidayAdjustmentSchool>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="学校补班调休列表">
      <template #table-title>
        <RadioGroup
          v-model:value="isDefault"
          button-style="solid"
          @change="handleChange"
        >
          <RadioButton :value="true"> 默认 </RadioButton>
          <RadioButton :value="false"> 自定义 </RadioButton>
        </RadioGroup>
      </template>
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['学校补班调休']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              ifShow: () => !isDefault,
              auth: ['edu:base:holiday-adjustment-school:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['edu:base:holiday-adjustment-school:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              ifShow: () => !isDefault,
              disabled: isEmpty(checkedIds),
              auth: ['edu:base:holiday-adjustment-school:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['edu:base:holiday-adjustment-school:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: row.status === CommonStatusEnum.ENABLE ? '禁用' : '启用',
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['edu:base:holiday-adjustment-school:update'],
              ifShow: () => isDefault,
              onClick: handleStatusChange.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              ifShow: () => !isDefault,
              auth: ['edu:base:holiday-adjustment-school:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              ifShow: () => !isDefault,
              auth: ['edu:base:holiday-adjustment-school:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
